import { Controller, Post, Body, UseInterceptors, UploadedFile } from '@nestjs/common';
import { UploadService } from './upload.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import path from 'path';
import fs from 'fs';

@Controller('upload')
export class UploadController {
  constructor(private readonly uploadService: UploadService) {
  }

  @Post('single')
  @UseInterceptors(FileInterceptor('file', {
    storage: diskStorage({
      destination(req, file, callback) {
        const { isChunk = 'false', fileHash } = req.body;
        const tempDir = isChunk === 'true' ? path.join(__dirname, '../resource/temp/chunked', fileHash) :
          path.join(__dirname, '../resource/temp/single')
        if (!fs.existsSync(tempDir)) {
          fs.mkdirSync(tempDir, { recursive: true })
        }
        callback(null, tempDir);
      },
      filename(req, file, callback) {
        const { index, filename, isChunk = 'false' } = req.body;
        const name = isChunk === 'true' ? `${index}-${filename}-${Date.now()}` :
          `${Date.now()}-${filename}`
        callback(null, name); //拼接索引+时间戳+文件名   防止乱序+覆盖
      },
    }),
    limits: { fileSize: 1024 * 1024 * 1024 * 10 } //限制文件大小  10G 
  }))
  uploadChunk(@UploadedFile() file: Express.Multer.File, @Body() body: any) {
    if (body.isChunk === 'true') {
      return this.uploadService.uploadChunk(file, body);
    } else {
      return this.uploadService.saveFile(file, body)
    }
  }

  @Post('checkChunk')
  checkChunk(@Body() body: any) {
    return this.uploadService.checkChunk(body)
  }



  @Post('merge')
  mergeChunks(@Body() body: any) {
    return this.uploadService.mergeChunks(body)
  }
} 